package com.wwdx.wechat.handler;

import com.wwdx.model.WwdxBookModel;
import com.wwdx.wechat.WxConstant;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @author liguoliang
 */
public abstract class AbstractScanHandler extends AbstractHandler {
    
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) {
        //二维码标识
        String eventKey = wxMessage.getEventKey();
        String falseString = Boolean.FALSE.toString();
        //赠一得一未被领取
        if (StringUtils.endsWith(eventKey, falseString)){
            String bookStr = StringUtils.substringBefore(eventKey, falseString);
            long bookid = Long.valueOf(bookStr);
            WwdxBookModel wwdxBookModel = wwdxBookService.getByBookId(bookid);
            String url = URIUtil.encodeURIComponent(wechatUrl+String.format(WxConstant.SINGLEBOOK_PAGE2,bookid,
                    wwdxBookModel.getVideoauthorid(),wwdxBookModel.getCopywriter()));
            String s = wechatUrl+"auth.html?url="+url;
            String content = "分享《"+wwdxBookModel.getBookname()+"》给好友，对方领取后即可免费听，" +
                    "<a href =\"%s"+"\">点击分享</a>";
            content = String.format(content,s);
            return WxMpXmlOutMessage.TEXT().content(content).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
        }
        return null;
    }
}